package com.farm.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.farm.dto.OrderDTO;
import com.farm.entity.Order;
import com.farm.entity.OrderStatus;
import com.farm.entity.User;
import com.farm.service.CartService;
import com.farm.service.OrderService;

@Controller
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private CartService cartService;

    @GetMapping("/orders")
    public String listOrders(@AuthenticationPrincipal User user, Model model) {
        List<Order> orders = orderService.findByUser(user);
        model.addAttribute("orders", orders);
        return "orders";
    }

    @GetMapping("/orders/{id}")
    public String orderDetail(@PathVariable Long id, Model model) {
        Order order = orderService.findById(id);
        model.addAttribute("order", order);
        return "order-detail";
    }

    @PostMapping("/cart/checkout")
    public String createOrder(
            @AuthenticationPrincipal User user,
            @RequestParam String contactName,
            @RequestParam String contactPhone,
            @RequestParam String deliveryAddress,
            RedirectAttributes redirectAttributes) {
        try {
            List<Order> orders = orderService.createOrdersFromCart(user, contactName, contactPhone, deliveryAddress);
            if (orders.size() == 1) {
                redirectAttributes.addFlashAttribute("message", "订单创建成功！");
                return "redirect:/orders/" + orders.get(0).getId();
            } else {
                redirectAttributes.addFlashAttribute("message", "成功创建 " + orders.size() + " 个订单！");
                return "redirect:/orders";
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/cart";
        }
    }

    @PostMapping("/orders/{id}/status")
    @ResponseBody
    public String updateOrderStatus(@PathVariable Long id, @RequestParam OrderStatus status, @AuthenticationPrincipal User user) {
        try {
            Order order = orderService.findById(id);
            
            // 检查权限
            if (status == OrderStatus.SHIPPED) {
                // 只有农户可以发货
                boolean isFarmer = order.getItems().stream()
                    .anyMatch(item -> item.getProduct().getFarmer().getId().equals(user.getId()));
                if (!isFarmer) {
                    return "error: 没有权限执行此操作";
                }
            } else if (status == OrderStatus.COMPLETED) {
                // 只有订单所有者可以确认收货
                if (!order.getUser().getId().equals(user.getId())) {
                    return "error: 没有权限执行此操作";
                }
            }
            
            orderService.updateOrderStatus(id, status);
            return "success";
        } catch (RuntimeException e) {
            return "error: " + e.getMessage();
        }
    }

    // Farmer endpoints
    @GetMapping("/farmer/orders")
    public String listFarmerOrders(@AuthenticationPrincipal User user, Model model) {
        List<Order> orders = orderService.findOrdersByFarmer(user);
        model.addAttribute("orders", orders);
        return "farmer/orders";
    }

    // Admin endpoints
    @GetMapping("/admin/orders")
    public String adminOrders(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            Model model) {
        List<Order> orders;
        if (keyword != null || status != null) {
            OrderStatus orderStatus = null;
            if (status != null && !status.isEmpty()) {
                try {
                    orderStatus = OrderStatus.valueOf(status);
                } catch (IllegalArgumentException e) {
                    // 忽略无效的状态值
                }
            }
            orders = orderService.searchOrders(keyword, orderStatus);
        } else {
            orders = orderService.findAllOrders();
        }
        model.addAttribute("orders", orders);
        return "admin/orders";
    }

    @PostMapping("/admin/orders/{id}/cancel")
    @ResponseBody
    public String cancelOrder(@PathVariable Long id) {
        try {
            orderService.updateOrderStatus(id, OrderStatus.CANCELLED);
            return "success";
        } catch (RuntimeException e) {
            return "error: " + e.getMessage();
        }
    }

    @GetMapping("/admin/orders/export")
    public void exportOrders(HttpServletResponse response) throws IOException {
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=\"orders.csv\"");
        
        List<Order> orders = orderService.findAllOrders();
        
        try (CSVPrinter csvPrinter = new CSVPrinter(response.getWriter(), CSVFormat.DEFAULT
                .withHeader("订单号", "下单时间", "买家", "农户", "商品数量", "总金额", "状态"))) {
            for (Order order : orders) {
                csvPrinter.printRecord(
                    order.getId(),
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getCreateTime()),
                    order.getUser().getRealName(),
                    order.getItems().stream()
                        .map(item -> item.getProduct().getFarmer().getRealName())
                        .distinct()
                        .collect(Collectors.joining(", ")),
                    order.getItems().size(),
                    order.getTotalAmount(),
                    getOrderStatusDisplayName(order.getStatus())
                );
            }
        }
    }

    @GetMapping("/admin/orders/{id}")
    @ResponseBody
    public ResponseEntity<OrderDTO> getOrder(@PathVariable Long id) {
        try {
            Order order = orderService.findById(id);
            if (order == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 转换为DTO避免序列化问题
            OrderDTO dto = new OrderDTO();
            dto.setId(order.getId());
            dto.setStatus(order.getStatus());
            dto.setContactName(order.getContactName());
            dto.setContactPhone(order.getContactPhone());
            dto.setDeliveryAddress(order.getDeliveryAddress());
            if (order.getUser() != null) {
                dto.setBuyerName(order.getUser().getRealName());
            }
            
            return ResponseEntity.ok(dto);
        } catch (Exception e) {
            log.error("Error fetching order: " + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PostMapping("/admin/orders/update")
    @ResponseBody
    public String updateOrder(@RequestBody Order order) {
        try {
            Order existingOrder = orderService.findById(order.getId());
            existingOrder.setContactName(order.getContactName());
            existingOrder.setContactPhone(order.getContactPhone());
            existingOrder.setDeliveryAddress(order.getDeliveryAddress());
            existingOrder.setStatus(order.getStatus());
            orderService.updateOrder(existingOrder);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    private String getOrderStatusDisplayName(OrderStatus status) {
        switch (status) {
            case PENDING:
                return "待发货";
            case SHIPPED:
                return "已发货";
            case COMPLETED:
                return "已完成";
            case CANCELLED:
                return "已取消";
            default:
                return status.name();
        }
    }
} 